package com.gx.auth.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.gx.auth.dao.UserInterfaceDAO;
import com.gx.auth.entity.User;

public class UserInterfaceImplDAO implements UserInterfaceDAO {
	private Connection conn = null;

	public UserInterfaceImplDAO(Connection conn) {
		this.conn = conn;
	}

	@Override
	public int insert(User t) throws SQLException {
		String sql = "insert into auth_user (u_name,u_pwd,createtime,updatetime) values (?,?,datetime('now', 'localtime'),datetime('now', 'localtime')) ";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setString(1, t.getUname());
		pst.setString(2, t.getUpwd());
		int count = pst.executeUpdate();
		pst.close();
		return count;
	}

	@Override
	public int delete(User t) throws SQLException {
		String sql = "delete from auth_user where u_name = ?";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setString(1, t.getUname());
		int count = pst.executeUpdate();
		pst.close();
		return count;
	}

	@Override
	public int update(User t) throws SQLException {
		String sql = "update  auth_user set u_pwd=?,updatetime=datetime('now', 'localtime')  where u_name = ?";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setString(1, t.getUpwd());
		pst.setString(2, t.getUname());
		int count = pst.executeUpdate();
		pst.close();
		return count;
	}

	@Override
	public User query(String name) throws SQLException {
		User user = new User();
		String sql = "select * from auth_user where u_name = ?";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setString(1, name);
		ResultSet rs = pst.executeQuery();
		if (rs.next()) {
			user = saveResult(rs);
		}
		rs.close();
		pst.close();
		return user;
	}

	@Override
	public List<User> queryAll() throws SQLException {
		List<User> ls = new ArrayList<>();
		String sql = "select * from auth_user ";
		PreparedStatement pst = conn.prepareStatement(sql);
		ResultSet rs = pst.executeQuery();
		while (rs.next()) {
			ls.add(saveResult(rs));
		}
		rs.close();
		pst.close();
		return ls;
	}

	@Override
	public User saveResult(ResultSet rs) throws SQLException {
		User user = new User();
		user.setUid(rs.getInt("u_id"));
		user.setUname(rs.getString("u_name"));
		user.setUpwd(rs.getString("u_pwd"));
		user.setCreatetime(rs.getString("createtime"));
		user.setUpdatetime(rs.getString("updatetime"));
		return user;
	}

}
